package com.freedo.demo.domain.imp;


import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freedo.demo.domain.i.IBaseDao;
import com.freedo.demo.domain.i.IUserDao;
import com.freedo.demo.entity.User;


@Repository(value="userDaoX")
public class UserDao implements IUserDao {

	@Resource
	private IBaseDao baseDao;
	
	
	static String INSERT_USER_SQL = ""; // 插入用户数据
	static String COUNT_USER_SQL="";	// 获取一个用户个数
	static String ONE_USER_SQL="";	// 获取一个用户
	static String ALL_USER_SQL="";	// 获取全部用户
	static String PAGE_USER_SQL=""; // 分页获取
	
	static {
		// 插入语句：添加用户
		INSERT_USER_SQL="insert into user(id,name,sex,age) values(?,?,?,?) ";
		COUNT_USER_SQL = "SELECT COUNT(*) FROM USER";
		ONE_USER_SQL = "select * from user where id = ?";
		ALL_USER_SQL = "select * from user";
		PAGE_USER_SQL = "select * from user limit ? , ?";
		
	}
	
	@Modifying
	@Transactional
	@Override
	public int insertUser(User u) {
		// TODO Auto-generated method stub
		Object[] params ={u.getId(),u.getName(),u.getSex(),u.getAge()}; 
		return baseDao.exec(INSERT_USER_SQL,params);
	}

	@Transactional
	@Override
	public User getUser(String id) {
		// TODO Auto-generated method stub
		Object[] params ={id};
		Object[] u =(Object[])baseDao.exec_single(ONE_USER_SQL,params);
		if(u==null)
		{
			return null;
		}
		return User.fromObject(u);
	}
	
	@Transactional
	@Override
	public int getUserCount() {
		// TODO Auto-generated method stub
		Object[] params= {};
		return baseDao.exec_count(COUNT_USER_SQL, params);
	}

	@Transactional
	@Override
	public List<User> getUsers() {
		// TODO Auto-generated method stub
		Object[] params ={}; 
		List<Object> us = baseDao.exec_list(ALL_USER_SQL,params);
		return User.fromObjectList(us);
	}

	@Transactional
	@Override
	public List<User> getUsersPage(int offset, int pagecount) {
		// TODO Auto-generated method stub
		Object[] params ={offset,pagecount}; 
		List<Object> us =baseDao.exec_list(PAGE_USER_SQL,params);
		return User.fromObjectList(us);
	}

}
